import Vue from 'vue';
import VueRouter from 'vue-router';

// 全局注册
Vue.use(VueRouter);

import Login from "../components/Login.vue";
import Home from "../components/Home.vue";

// 主页面/home---主体内容部分的组件
import Welcome from '../components/Welcome.vue';
import Users from "../components/01_users/Users.vue";
import Roles from "../components/02_rights/Roles.vue";
import Rights from "../components/02_rights/Rights.vue";
import Goods from "../components/03_goods/Goods.vue";
import Params from "../components/03_goods/Params.vue";
import AddGoodsPage from "../components/03_goods/AddGoodsPage.vue";
import Categories from "../components/03_goods/Categories.vue";
import Orders from "../components/04_orders/Orders.vue";
import Reports from "../components/05_reports/Reports.vue";


// 路由对象
const router = new VueRouter({
  routes :[
    // 路由规则写在这里
    { path: '/', redirect: "/login" },   //重定向,一进入网站就进入登录页面
    { path: '/login', component: Login },
    { 
      path: '/home', 
      component: Home,
      children:[
        // 子路由
        {path:'/welcome',component:Welcome},
        {path:'/users',component:Users},
        {path:'/roles',component:Roles},
        {path:'/rights',component:Rights},
        {path:'/goods',component:Goods},
        {path:'/addgoodspage',component:AddGoodsPage},
        {path:'/params',component:Params},
        {path:'/categories',component:Categories},
        {path:'/orders',component:Orders},
        {path:'/reports',component:Reports},

      ],
      redirect:'/welcome'
    }
  ]
})

// 为路由对象,添加beforeEach路由守卫-->控制访问权限
router.beforeEach((to, from, next) => {
    /*
      to将要访问的路径
      from 代表从哪个路径跳转而来
      next是一个函数，表示放行
        next()放行  next('/login')强制跳转
    */
    //访问登录页面，直接放行
    if(to.path === "/login")  next();
    //访问其他页面
    else{
      //获取token
      const tokenValue = window.sessionStorage.getItem('token');
      if(tokenValue)  
        next();
      else{
        alert("您还未登录，请先去完成登录！！！");
        next("/login");
      }
    }
  }
)

export default router;

// 使用方法/跳转方法： this.$router.push('路由规则中的hash路径');
